<template>
  <div>
    <el-dialog
      title="为当前角色分配权限"
      :model-value="modelValue"
      width="30%"
      @close="closed"
    >
      <el-tree
        ref="treeRef"
        :data="allPermissionList"
        show-checkbox
        node-key="id"
        :default-expanded-keys="['1', '2', '3', '4', '5', '6', '7']"
        :default-checked-keys="checkedKeys"
        :props="defaultProps"
        :check-strictly="true"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closed">取消</el-button>
          <el-button @click="onConfirm" type="primary">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { permissionList } from '@/api/permission'
import { rolePermission, distributePermission } from '@/api/role'
import { ElMessage } from 'element-plus'
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String
  }
})

const allPermissionList = ref([])
const checkedKeys = ref([])
const treeRef = ref(null)
const emits = defineEmits(['update:modelValue'])
const defaultProps = {
  label: 'permissionName',
  children: 'children'
}

// 获取所有的权限列表
const getAllPermissionList = async () => {
  allPermissionList.value = await permissionList()
  console.log(JSON.stringify(allPermissionList.value, null, 4))
}

// 获取指定角色权限
const getRolePermission = async () => {
  checkedKeys.value = await rolePermission(props.roleId)
  console.log(JSON.stringify(checkedKeys.value, null, 4))
}
watch(() => props.modelValue, (modelValue) => {
  console.log('modelValue', modelValue)
  if (modelValue) {
    getRolePermission()
    getAllPermissionList()
  } else {
    checkedKeys.value = []
    allPermissionList.value = []
  }
}, {
  immediate: true
})

const closed = () => {
  emits('update:modelValue', false)
}
const onConfirm = async () => {
  const checkeds = treeRef.value.getCheckedKeys(false)
  await distributePermission(props.roleId, checkeds)
  ElMessage.success('设置成功')
  closed()
}

</script>

<style>

</style>
